<template>
    <div class="note-dashboard">
        <!-- 内容区域 -->
        <div class="content-area">
            <!-- 顶部按钮区 -->
            <div class="top-nav">
                <div class="left-buttons">
                    <el-button 
                        class="action-btn" 
                        @click="navigateToNoteEditor"
                    >
                        <el-icon><EditPen /></el-icon>
                        写笔记
                    </el-button>
                    <el-button 
                        class="action-btn"
                        @click="navigateToCloudDisk"
                    >
                        <el-icon><FolderOpened /></el-icon>
                        我的云盘
                    </el-button>
                </div>
                <div class="center-text">我的</div>
                <el-button 
                    class="refresh-btn" 
                    @click="handleRefresh"
                >
                    <el-icon :class="{ 'rotating': isRefreshing }"><Refresh /></el-icon>
                    刷新
                </el-button>
            </div>

            <!-- 笔记本标题区域和搜索框 -->
            <div class="notebook-header">
                <div class="notebook-section">
                    <el-icon size="24" color="#67C23A"><Notebook /></el-icon>
                    <span class="notebook-text">记事本</span>
                </div>
                <div class="search-box">
                    <el-input
                        v-model="searchText"
                        placeholder="搜索笔记..."
                        class="search-input"
                    >
                        <template #suffix>
                            <el-icon><Search /></el-icon>
                        </template>
                    </el-input>
                </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-section">
                <!-- 发表评论按钮 -->
                <div class="comment-button-container">
                    <div class="left-buttons">
                        <el-button 
                            class="action-btn" 
                            @click="showCommentDialog"
                        >
                            <el-icon><EditPen /></el-icon>
                            发表评论
                        </el-button>
                    </div>
                    <div class="right-buttons">
                        <el-button 
                            class="action-btn"
                            @click="navigateToRoot"
                        >
                            根目录
                            <el-icon><ArrowRight /></el-icon>
                        </el-button>
                    </div>
                </div>

                <!-- 评论列表 -->
                <div class="comment-list">
                    <el-empty v-if="!comments.length" description="暂无评论" />
                    <div 
                        v-else
                        v-loading="isLoadingComments"
                        class="comments-container"
                    >
                        <div 
                            v-for="comment in comments" 
                            :key="comment.id" 
                            class="comment"
                        >
                            <div class="comment-header">
                                <div class="user-info">
                                    <el-avatar :src="comment.avatar" />
                                    <span class="username">{{ comment.username }}</span>
                                </div>
                            </div>
                            <div class="comment-content">{{ comment.content }}</div>
                            <div class="comment-footer">
                                <div class="comment-info">
                                    <span class="comment-time">{{ formatTime(comment.time) }}</span>
                                    <span class="views">
                                        <el-icon><View /></el-icon>
                                        {{ comment.views }}
                                    </span>
                                </div>
                                <div class="comment-actions">
                                    <el-button text size="small" @click="handleReply(comment)">
                                        <el-icon><ChatDotRound /></el-icon>评论
                                    </el-button>
                                    <el-button text size="small" @click="handleShare(comment)">
                                        <el-icon><Share /></el-icon>转发
                                    </el-button>
                                    <el-button text size="small" @click="handleLike(comment)">
                                        <el-icon><Star /></el-icon>点赞
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 分页 -->
                <div class="pagination">
                    <Pagination 
                        ref="notePagination"
                        v-model:currentPage="currentPage"
                        v-model:pageSize="pageSize"
                        v-model:total="total"
                        @updateData="handleUpdateData"
                    />
                </div>
            </div>

            <!-- 评论弹框 -->
            <el-dialog
                v-model="commentDialogVisible"
                title="发表评论"
                width="500px"
                :show-close="true"
                :close-on-click-modal="false"
            >
                <div class="comment-dialog-content">
                    <el-input
                        v-model="newCommentText"
                        type="textarea"
                        :rows="4"
                        placeholder="写下你的评论..."
                        resize="none"
                    />
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="commentDialogVisible = false">取消</el-button>
                        <el-button 
                            type="primary" 
                            @click="handleAddComment"
                            :loading="isSubmitting"
                        >
                            发表
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, inject, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useNoteStore } from '@/store/modules/note/noteStore';
import { Comment } from '@/types/note/comment';
import {
    Search,
    Refresh,
    EditPen,
    FolderOpened,
    Notebook,
    ArrowRight,
    View,
    Share,
    Star,
    ChatDotRound
} from '@element-plus/icons-vue';
import Pagination from '@/components/Pagination.vue';

// 类型定义


// 状态管理
const router = useRouter();
const noteStore = useNoteStore();
const searchText = ref('');
const isRefreshing = ref(false);
const newCommentText = ref('');
const isSubmitting = ref(false);
const isLoadingComments = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 评论列表
const comments = ref<Comment[]>([]);

// 分页相关数据
const notePagination = ref();

// 添加新的响应式变量
const commentDialogVisible = ref(false);

// 初始化数据
onMounted(async () => {
    await fetchComments();
});

// 获取评论列表
const fetchComments = async (page = 1) => {
    isLoadingComments.value = true;
    try {
        // 模拟数据，实际项目中替换为API调用
        comments.value = [{
            id: 1,
            avatar: 'https://picsum.photos/50/50',
            username: '用户1',
            content: '这是一条评论',
            time: new Date(),
            views: 100,
            likes: 10,
            replies: []
        }];
        total.value = 1;
    } catch (error) {
        console.error('Failed to fetch comments:', error);
        ElMessage.error('获取评论失败');
    } finally {
        isLoadingComments.value = false;
    }
};

// 处理评论提交
const handleAddComment = async () => {
    if (!newCommentText.value.trim()) {
        ElMessage.warning('请输入评论内容');
        return;
    }

    isSubmitting.value = true;
    try {
        // 模拟添加评论
        const newComment: Comment = {
            id: comments.value.length + 1,
            avatar: 'https://picsum.photos/50/50',
            username: '当前用户',
            content: newCommentText.value,
            time: new Date(),
            views: 0,
            likes: 0,
            replies: []
        };
        comments.value.unshift(newComment);
        newCommentText.value = '';
        ElMessage.success('评论成功');
        commentDialogVisible.value = false; // 提交成功后关闭弹框
    } catch (error) {
        ElMessage.error('评论失败');
    } finally {
        isSubmitting.value = false;
    }
};

// 处理数据更新
const handleUpdateData = (currentPage: number, pageSize: number) => {
    console.log('更新数据\n当前页码：' + currentPage, '每页条数：' + pageSize);
    fetchComments(currentPage);
};

// 导航方法
const navigateToNoteEditor = () => {
    try {
        router.push('/note/notewrite');
    } catch (error) {
        console.error('Navigation error:', error);
        ElMessage.error('导航失败');
    }
};

const navigateToCloudDisk = (path = '/') => {
    try {
        router.push({
            path: '/note/clouddisk',
            query: { path }
        });
    } catch (error) {
        console.error('Navigation error:', error);
        ElMessage.error('导航失败');
    }
};

// 目录导航
const navigateToRoot = () => {
    navigateToCloudDisk();
};

// 刷新处理
const handleRefresh = async () => {
    if (isRefreshing.value) return;
    
    isRefreshing.value = true;
    try {
        await fetchData();
        ElMessage.success('刷新成功');
    } catch (error) {
        ElMessage.error('刷新失败');
    } finally {
        setTimeout(() => {
            isRefreshing.value = false;
        }, 1000); // 确保画至少显示1秒
    }
};


// 定义搜索函数
const searchFunction = (input: string): void => {
    console.log('笔记搜索：', input);

    // 自己处理数据
    noteStore.notes
        .filter(note => 
            note.noteTitle.toLowerCase().includes(input.toLowerCase()) ||
            note.noteContent.toLowerCase().includes(input.toLowerCase())
        )
        .map(note => ({
            title: note.noteTitle,
            path: `/note/notewrite?id=${note.noteId}`
        }));
};

// 定义搜索提示函数
const searchPromptFunction = (input: string): Array<Object> => {
    console.log('笔记搜索提示：', input);
    return noteStore.notes
        .filter(note => note.noteTitle.toLowerCase().includes(input.toLowerCase()))
        .slice(0, 5)
        .map(note => ({
            title: note.noteTitle,
            path: `/note/notewrite?id=${note.noteId}`
        }));
};

// 注入父组件提供的函数
const takeOverSearch = inject<(
    search: (input: string) => void,
    prompt: (input: string) => Array<Object>,
    placeholder: string | undefined
) => void>("takeOverSearch");

const releaseSearch = inject<() => void>("releaseSearch");

onMounted(() => {
    // 接管搜索事件
    if (takeOverSearch) {
        takeOverSearch(searchFunction, searchPromptFunction, "搜索笔记");
    }
});

onUnmounted(() => {
    // 释放搜索事件
    if (releaseSearch) {
        releaseSearch();
    }
});

// 搜索处理
const handleSearch = () => {
    if (!searchText.value.trim()) {
        ElMessage.warning('请输入搜索内容');
        return;
    }
    // 实现搜索逻辑
    console.log('Searching:', searchText.value);
};

// 评论相关方法
const formatTime = (time: Date) => {
    const date = new Date(time);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
};

const handleShare = async (comment: Comment) => {
    try {
        await ElMessageBox.confirm('确定要转发这条评论吗？', '转发确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
        });
        ElMessage.success('转发成功');
    } catch {
        // 用户取消操作
    }
};

const handleLike = (comment: Comment) => {
    // 实现点赞逻辑
    comment.likes++;
    ElMessage.success('点赞成功');
};

const handleReply = (comment: Comment) => {
    ElMessageBox.prompt('请输入回复内容', '回复', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(({ value }) => {
        if (value) {
            comment.replies = comment.replies || [];
            comment.replies.push({
                id: Date.now(),
                avatar: 'https://placeholder.com/50',
                username: '当前用户',
                content: value,
                time: new Date(),
                views: 0,
                likes: 0,
                replies: []
            });
            ElMessage.success('回复成功');
        }
    }).catch(() => {
        // 用户取消操作
    });
};

// 数据获取
const fetchData = async () => {
    try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        // 这里可以添加实际的API调用
    } catch (error) {
        console.error('Error fetching data:', error);
        throw error;
    }
};

// 初始化
onMounted(async () => {
    try {
        await fetchData();
    } catch (error) {
        ElMessage.error('数据加载失败');
    }
});

// 显示评论弹框
const showCommentDialog = () => {
    commentDialogVisible.value = true;
    newCommentText.value = '';
};
</script>

<style scoped>
.note-dashboard {
    width: 100%;
    min-height: calc(100vh - 60px);
    padding: 0;
    margin-top: 60px;
    display: flex;
    justify-content: center;
    /* background: #f5f7fa; */
}

.content-area {
    width: var(--width);
    margin: 20px auto;
    background: #f5f7fa98;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
    min-height: calc(100vh - 100px);
}

/* 顶部按钮区域 */
.top-nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    position: relative;
}

.left-buttons {
    display: flex;
    gap: 12px;
}

.action-btn {
    background: #f0f7ff;
    border: 1px solid #409EFF;
    color: #409EFF;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.refresh-btn {
    background: none;
    border: none;
    color: #606266;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.refresh-btn:hover {
    color: #409EFF;
}

/* 旋转动画 */
.rotating {
    animation: rotate 1s linear infinite;
}

@keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* 内容区域的内边距 */
.notebook-header,
.search-nav-section,
.comments-section {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
}

.notebook-section {
    display: flex;
    align-items: center;
    gap: 8px;
}

.notebook-text {
    color: #67C23A;
    font-size: 16px;
    font-weight: 500;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
    .content-area {
        width: 95%;
        margin: 60px auto 20px;
    }
    
    .top-nav {
        top: -40px;
    }
}

.notebook-header {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-box {
    display: flex;
    align-items: center;
    gap: 12px;
}

.search-input {
    width: 300px;
}

.search-input :deep(.el-input__wrapper) {
    border-radius: 20px;
    background-color: #f5f7fa;
    padding: 0 16px;
}

.search-input :deep(.el-input__prefix) {
    color: #909399;
    font-size: 16px;
    margin-right: 8px;
}

.search-input :deep(.el-input__inner) {
    height: 36px;
}

.search-input :deep(.el-input__inner)::placeholder {
    color: #909399;
}

.refresh-btn {
    color: #606266;
    border: 1px solid #dcdfe6;
    padding: 8px;
    border-radius: 4px;
}

.comment-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    color: #909399;
    font-size: 13px;
}

.comment-info {
    display: flex;
    align-items: center;
    gap: 16px;
}

.comment-time {
    color: #909399;
}

.views {
    display: flex;
    align-items: center;
    gap: 4px;
}

.comment-actions {
    display: flex;
    align-items: center;
    gap: 16px;
}

.comment-actions .el-button {
    color: #909399;
    font-size: 13px;
}

.comment-actions .el-button:hover {
    color: #409EFF;
}

.comment-actions .el-icon {
    margin-right: 4px;
}

.comment-button-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0;
}

.left-buttons, .right-buttons {
    display: flex;
    gap: 12px;
}

.action-btn {
    background: #f0f7ff;
    border: 1px solid #409EFF;
    color: #409EFF;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.action-btn:hover {
    transform: translateY(-2px);
    transition: all 0.3s;
}

.comment-dialog-content {
    padding: 20px 0;
}

:deep(.el-dialog) {
    border-radius: 8px;
    background: #f5f7fa;
}

:deep(.el-dialog__header) {
    margin-right: 0;
}

:deep(.el-dialog__body) {
    padding: 0 20px;
}

:deep(.el-dialog__footer) {
    padding: 20px;
    border-top: 1px solid #ebeef5;
}

.dialog-footer {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.username {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
}

.center-text {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-size: 28px;
    font-weight: 550;
    color: #303133;
}
</style>
